package com.coalmine.api.plugin.dm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.coalmine.api.domain.ApiConfig;
import com.coalmine.api.plugin.CachePlugin;
import com.coalmine.api.plugin.PluginConf;
import com.coalmine.api.util.YamlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


import java.util.List;
import java.util.Map;

@Component
public class RedisCachePlugin extends CachePlugin {

    JedisPool pool;

    public void testCollection() {
        Jedis resource = pool.getResource();
    }

  /*  private static String apiContext;

    public static String getContext() {
        return apiContext;
    }

    @Value("${datamanage.api.context}")
    public void setConfig1(String apiContext) {
        RedisCachePlugin.apiContext = apiContext;
    }*/

    @Override
    public void init() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(200);
        config.setMaxIdle(50);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        String host = YamlUtil.instance.getValue("spring.redis.host");
        String port = YamlUtil.instance.getValue("spring.redis.port");
        String database = YamlUtil.instance.getValue("spring.redis.database");
        String password = YamlUtil.instance.getValue("spring.redis.password");
        if (StringUtils.isNotBlank(password)&&!("null").equals(password)) {
            this.pool = new JedisPool(config, host,
                    Integer.parseInt(port), 100, password,
                    Integer.parseInt(database));
        } else {
            this.pool = new JedisPool(config, host,
                    Integer.parseInt(port), 100, null,
                    Integer.parseInt(database));
        }
        super.logger.info("init jedis pool success");
    }

    @Override
    public void set(ApiConfig apiConfig, Map<String, Object> map, Object data) {
        // redis缓存时间
        String expireTime = apiConfig.getCachePluginParams();
        super.logger.debug("set data to cache");
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String key ="api:" + apiConfig.getId()+":"+ apiConfig.getRealServletPath();
            String hashKey = "";
            for (Object o : map.values()) {
                hashKey += o.toString() + "-";
            }
            jedis.hset(key, hashKey, JSON.toJSONString(data));
            // 设置过期时间，过期时间从插件参数传过来
            if (StringUtils.isNotBlank(expireTime)) {
                jedis.expire(key, Integer.parseInt(expireTime));
            }
        } catch (Exception e) {
            super.logger.error("设置缓存失败", e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    @Override
    public void clean(ApiConfig apiConfig) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String key = "api:" + apiConfig.getId()+":"+ apiConfig.getRealServletPath();
            jedis.del(key);
        } catch (Exception e) {
            super.logger.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    @Override
    public Object get(ApiConfig apiConfig, Map<String, Object> map) {
        super.logger.debug("get data from cache");
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String key = "api:" + apiConfig.getId()+":"+ apiConfig.getRealServletPath();
            String hashKey = "";
            for (Object o : map.values()) {
                hashKey += o.toString() + "-";
            }
            String hget = jedis.hget(key, hashKey);
            return JSONObject.parse(hget);
        } catch (Exception e) {
            super.logger.error("查询缓存失败", e);
            return null;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
